import 'dart:async';
import 'dart:collection';
import 'package:df/page/web/js_callback.dart';
import 'package:df/page/web/permission_key.dart';
import 'package:df/page/web/web_page.dart';
import 'package:df/utils/logger_utils.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:go_router/go_router.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:df/generated/l10n.dart';


class TestWeb extends StatefulWidget {
  final String wechatUnionId;
  final String larkUnionId;
  final String userId;
  const TestWeb({Key? key, required this.wechatUnionId, required this.larkUnionId, required this.userId}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TestWebState();
  }
}

class _TestWebState extends State<TestWeb> {
  _TestWebState();

  final GlobalKey webViewKey = GlobalKey();
  double progress = 0;
  final urlController = TextEditingController();
  PullToRefreshController? pullToRefreshController;
  InAppWebViewSettings settings = InAppWebViewSettings(
      isInspectable: kDebugMode,
      mediaPlaybackRequiresUserGesture: false,
      allowsInlineMediaPlayback: true,
      iframeAllow: "${PermissionKey.kCamera}}",//TODO 权限//
      // iframeAllow: "${PermissionKey.kCamera}; ${PermissionKey.kMicrophone}",
      iframeAllowFullscreen: true);
  InAppWebViewSettings settings1 = kInAppWebViewSettings;
  InAppWebViewController? inAppWebViewController;

  @override
  void initState() {
    super.initState();

    pullToRefreshController = kIsWeb || ![TargetPlatform.iOS, TargetPlatform.android].contains(defaultTargetPlatform)
        ? null
        : PullToRefreshController(
      settings: PullToRefreshSettings(
        color: Colors.cyan,
      ),
      onRefresh: () async {
        if (defaultTargetPlatform == TargetPlatform.android) {
          inAppWebViewController?.reload();
        } else if (defaultTargetPlatform == TargetPlatform.iOS) {
          inAppWebViewController?.loadUrl(urlRequest: URLRequest(url: await inAppWebViewController?.getUrl()));
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return buildScaffold1(context);
  }

  Widget buildScaffold1(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Text('Web调试'),
          leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              GoRouter.of(context).pop();
            },
          ),
          actions: [
            IconButton(
              icon: Icon(Icons.camera_alt),
              onPressed: () {

                Future<PermissionStatus>? status = requestCamera(PermissionKey.kCamera);
                status?.then((permissionStatus) {
                  // 申请摄像头权限
                  if (permissionStatus.isGranted) {
                    // 权限已授予，可以进行摄像头相关操作
                    LogUtils.w('已获取摄像头权限');
                    ToastUtils.show(S.current.authorizedCamera);
                  } else {
                    // 用户拒绝了权限请求
                    LogUtils.e('(拒绝)相机权限');
                    ToastUtils.show(S.current.cameraPermissionDenied);
                  }
                });

              },
            ),
          ]

      ),

      body: buildSafeArea2(context),
    );
  }

  Widget buildSafeArea2(BuildContext context) {
    return SafeArea(
      top: true,
      bottom: false,
      left: false,
      right: false,

      child: buildWillPopScope3(context),

    );
  }

  Widget buildWillPopScope3(BuildContext context) {
    bool _doubleBackToExitPressedOnce = false;

    return WillPopScope(
      onWillPop: () async {
        if (await inAppWebViewController?.canGoBack() ?? false) {
          inAppWebViewController?.goBack();
          return false;
        } else {
          if (_doubleBackToExitPressedOnce) {
            return true;
          }
          _doubleBackToExitPressedOnce = true;
          ToastUtils.show(S.current.exitAgain);

          // 如果 2 秒内再次按下，则退出应用
          Future.delayed(Duration(seconds: 2), () {
            _doubleBackToExitPressedOnce = false;
          });

          return false;
        }
      },

      child: buildStack4(context),

    );
  }

  Widget buildStack4(BuildContext context) {
    return Stack(
      children: [
        buildInAppWebView5(context),
        (progress < 1.0) ? LinearProgressIndicator(value: progress) : Container(),
      ],
    );
  }

  Widget buildInAppWebView5(BuildContext context) {
    final Completer<InAppWebViewController> controllerCompleter = Completer<InAppWebViewController>();

    return InAppWebView(
      //【JsFlutter-2/2】==============================================
      // initialData: InAppWebViewInitialData(data: htmlData),
      // initialUrlRequest: URLRequest(url: WebUri('https://192.168.162.128:3000/')),
      initialUrlRequest: URLRequest(url: WebUri('https://sps.pheyma.com/wxhhapps/index.html#/Mine/wxUnionId=ok-Ft6Fan2WipBocq_NzlK2Yy790&flyUnionId=on_4ef6c0235db38923b0d6002c5fa39f0a&userId=4660028360051142119&platform=android')),
      //【JsFlutter-2/2】==============================================
      // 禁用 SSL 证书验证，总是信任
      onReceivedServerTrustAuthRequest: (controller, challenge) async {
        return ServerTrustAuthResponse(action: ServerTrustAuthResponseAction.PROCEED);
      },
      onConsoleMessage: (controller, consoleMessage) {
        LogUtils.d(
            '=============================================================================================================='
                '\n【Js控制台】\n${consoleMessage}\n'
                '=============================================================================================================='
        );
      },
      onWebViewCreated: (controller) async {
        inAppWebViewController = controller;
        controllerCompleter.complete(controller);
        controllerCompleter.future.then((value) {

        });
        addJsHandler(context, controller);
      },
      initialUserScripts: UnmodifiableListView<UserScript>([]),
      key: webViewKey,
      pullToRefreshController: pullToRefreshController,
      initialSettings: settings,
      onLoadStart: (controller, url) async {
        setState(() {
          urlController.text = url.toString();
          LogUtils.w('【浏览器】Url= ${url.toString()}');
        });
      },
      onPermissionRequest: (controller, request) async {
        return PermissionResponse(//TODO 权限
            resources: request.resources,
            action: PermissionResponseAction.GRANT);
      },
      shouldOverrideUrlLoading:
          (controller, navigationAction) async {
        var uri = navigationAction.request.url!;
        if (![
          "http",
          "https",
          "file",
          "chrome",
          "data",
          "javascript",
          "about"
        ].contains(uri.scheme)) {
          if (await canLaunchUrl(uri)) {
            // Launch the App
            await launchUrl(
              uri,
            );
            // and cancel the request
            return NavigationActionPolicy.CANCEL;
          }
        }

        return NavigationActionPolicy.ALLOW;
      },
      onLoadStop: (controller, url) async {
        pullToRefreshController?.endRefreshing();
        setState(() {
          urlController.text = url.toString();
        });
        String? pageTitle = await controller.getTitle();
        LogUtils.w("【浏览器】标题= ${pageTitle}");
      },
      onReceivedError: (controller, request, error) {
        pullToRefreshController?.endRefreshing();
      },
      onProgressChanged: (controller, progress) {
        if (progress == 100) {
          pullToRefreshController?.endRefreshing();
        }
        setState(() {
          this.progress = progress / 100;
          //TODO urlController.text = url.toString();
        });
      },
      onUpdateVisitedHistory: (controller, url, isReload) {
        setState(() {
          urlController.text = url.toString();
        });
      },
    );
  }

  /// https://blog.csdn.net/gloryFlow/article/details/133643136
  void addJsHandler(BuildContext context,InAppWebViewController? controller) {
    String platform = "";
    if (Platform.isAndroid) {
      platform = 'android';
    } else if (Platform.isIOS) {
      platform = 'ios';
    } else {
      platform = 'unknown';
    }

    controller?.addJavaScriptHandler(
        handlerName: 'jsRequestPermission', //现场管理->照片登记
        callback: (parameters) async {
          PermissionStatus? status = await requestCamera(PermissionKey.kCamera);

          if (status != null && status.isGranted) {
            // 权限已授予，可以进行摄像头相关操作
            LogUtils.w('已获取摄像头权限');
            ToastUtils.show(S.current.authorizedCamera);

            // Flutter返回给Js。
            List<String> permission = []; //List<String>();
            permission.add(PermissionKey.kCamera);
            JsCallback callback = JsCallback(platform: platform, permission: permission);

            //callback.permission = permission;
            return callback;
          } else {
            LogUtils.e('已(拒绝)摄像头权限');
            ToastUtils.show(S.current.cameraPermissionDenied);

            // Flutter返回给Js。
            JsCallback callback = JsCallback(platform: platform, permission: []);
            return callback;
          }
        });
  }



  Future<PermissionStatus>? requestCamera(String permissionKey) async {
    var status;
    if(PermissionKey.kCamera == permissionKey){
      status = await Permission.camera.request();
    } else {
      ToastUtils.show(S.current.noMatchThesePermissions);
    }
    return status;
  }

  //https://blog.csdn.net/Nean_Zhou/article/details/127172673
  Future<Map<Permission, PermissionStatus>> requestPermissions(List<String> permissionKeys) async {
    Map<Permission, PermissionStatus> statusMap = {};

    // for (Permission permission in permissionKeys[""]) {
    //   if (PermissionKey.kCamera == permission) {
    //       PermissionStatus status = await permission.request();
    //       statusMap[permission] = status;
    //   } else {
    //       ToastUtils.show(S.current.noMatchThesePermissions);
    //   }
    // }

    return statusMap;
  }

}

